package com.aopcinemas.visitor.behaviour;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

import java.util.List;

import com.aopcinemas.cinema.CinemaConstants;
import com.aopcinemas.visitor.VisitorAgent;

public class CinemaListUpdateBehaviour extends TickerBehaviour {

    private static final long serialVersionUID = 1L;
    private List<AID> cinemas;

    public CinemaListUpdateBehaviour(Agent agent, long period) {
        super(agent, period);
        cinemas = ((VisitorAgent) agent).getCinemas();
    }

    @Override
    protected void onTick() {
        DFAgentDescription template = new DFAgentDescription();
        ServiceDescription sd = new ServiceDescription();
        sd.setType(CinemaConstants.CINEMA_SERVICE_TYPE);
        template.addServices(sd);

        try {
            cinemas.clear();
            DFAgentDescription[] result = DFService.search(myAgent, template);
            System.out.println("found cinem cervices: " + result.length);
            for (int i = 0; i < result.length; ++i) {
                cinemas.add(result[i].getName());
            }
        } catch (FIPAException e) {
            throw new RuntimeException("Can't find cinemas");
        }

    }

}
